package com.mzy.basics.serializable.jsontoolclass;


import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import org.testng.annotations.Test;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Ives
 * * @date 2021/11/22
 */
public class GsonTest {

  /**
   * JSON 字符串转换为Java 对象
   */
  @Test
  public void test(){
    // gson无法正常将时间戳转化成date
    // 使用JSON内存树注册Date类型
    final Gson gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
              @Override
              public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
                return new Date(jsonElement.getAsJsonPrimitive().getAsLong());
              }
            }).create();

    String json = "{\"createTime\":1621341922450,\"id\":1,\"name\":\"DT\"}";
    Person person = gson.fromJson(json, Person.class);
    System.out.println("java对象->>>"+person);
  }

  /**
   * 将Java对象转换为JSON 字符串
   */
  @Test
  public void test2(){
    Gson gson = new Gson();
    Person person = new Person(1,"DT",new Date());
    String json = gson.toJson(person);
    System.out.println("json字符串->>>"+json);

  }

  /**
   * 将JSON 字符串数组转为JSON数组
   */
  @Test
  public void test3(){
    // gson无法正常将时间戳转化成date
    // 使用JSON内存树注册Date类型
    final Gson gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
              @Override
              public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
                return new Date(jsonElement.getAsJsonPrimitive().getAsLong());
              }
            }).create();

    String json = "[{\"id\":1,\"name\":\"张三\",\"createTime\":1622719597081}, {\"id\":2,\"name\":\"李四\",\"createTime\":1622719597081}]";
    Type type = new TypeToken<ArrayList<Person>>(){}.getType();
    List<Person> personList = gson.fromJson(json, type);
    personList.stream().forEach(System.out::println);
  }

  /**
   * 将JSON数组转为JSON 字符串
   */
  @Test
  public void test4(){
    Gson gson = new Gson();
    List<Person> personList = new ArrayList<>();
    personList.add(new Person(1,"DT",new Date()));
    personList.add(new Person(2,"DT1",new Date()));
    personList.add(new Person(3,"DT2",new Date()));
    String json = gson.toJson(personList);
    System.out.println("json->>>"+json);

  }
}
